<?php

namespace App\Traits\Response;

use Symfony\Component\HttpFoundation\Response;

trait InterfaceResponse
{
    /**
     * 定义默认响应状态码
     *
     * @var int
     */
    protected $statusCode = Response::HTTP_OK;

    /**
     * 设置响应状态吗
     *
     * @param $statusCode
     * @return $this
     */
    public function setStatusCode($statusCode)
    {
        $this->statusCode = $statusCode;
        return $this;
    }

    /**
     * 创建资源成功响应
     *
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function stored($data)
    {
        return $this->setStatusCode(Response::HTTP_CREATED)->respond($data);
    }

    /**
     * 更新资源成功的响应
     *
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function updated($data)
    {
        return $this->setStatusCode(Response::HTTP_OK)->respond($data);
    }

    /**
     * 删除资源成功响应
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function deleted()
    {
        return $this->setStatusCode(Response::HTTP_NO_CONTENT)->respond();
    }

    /**
     * 异步任务响应
     *
     * @param $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function accepted($message)
    {
        return $this->setStatusCode(Response::HTTP_ACCEPTED)->message($message);
    }

    /**
     * 资源不存在
     *
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function notFound($message = 'Not Found')
    {
        return $this->failed($message, Response::HTTP_NOT_FOUND);
    }

    /**
     * 服务器未知错误
     *
     * @param string $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function internalError($message = 'Internal Error')
    {
        return $this->failed($message, Response::HTTP_INTERNAL_SERVER_ERROR);
    }

    /**
     * 未知错误响应
     *
     * @param $message
     * @param boolean $code
     * @return \Illuminate\Http\JsonResponse
     */
    public function failed($message, $code = false)
    {
        return $this->setStatusCode($code ? $code : Response::HTTP_BAD_REQUEST)->message($message);
    }

    /**
     * 响应资源
     *
     * @param $data
     * @return \Illuminate\Http\JsonResponse
     */
    public function success($data)
    {
        return $this->respond($data);
    }

    /**
     * 响应消息
     *
     * @param $message
     * @return \Illuminate\Http\JsonResponse
     */
    public function message($message)
    {
        return $this->respond([
            'error' => $message
        ]);
    }

    /**
     * 生成响应
     *
     * @param $data
     * @param array $header
     * @return \Illuminate\Http\JsonResponse
     */
    public function respond($data = [], array $header = [])
    {
        return response()->json($data, $this->statusCode, $header);
    }
}
